﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using EasySamba.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace EasySamba.Controllers
{
    public class LoginController : Controller
    {
        public IActionResult Index(string returnUrl)
        {
            var loginViewModel = new LoginViewModel();
            loginViewModel.ReturnUrl = returnUrl;
            return View(loginViewModel);
        }

        [HttpPost]
        public async Task<ActionResult> Login(LoginViewModel loginViewModel)
        {
            var result = new Result(false, string.Empty);

            if (!ModelState.IsValid)
            {
                return RedirectToAction("Index");
            }

            var adminPassword = Startup.Configuration["Password"];
            if (loginViewModel.Password == adminPassword)
            {
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);//一定要声明AuthenticationScheme
                identity.AddClaim(new Claim(ClaimTypes.Name, adminPassword));

                await HttpContext.SignInAsync(identity.AuthenticationType,
                                              new ClaimsPrincipal(identity),
                                              new AuthenticationProperties
                                              {
                                                  IsPersistent = true,
                                                  RedirectUri = loginViewModel.ReturnUrl ?? "/Easy/Index",
                                              });

                if (!string.IsNullOrEmpty(loginViewModel.ReturnUrl))
                {
                    return Redirect(loginViewModel.ReturnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Easy");
                }
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
    }
}
